//
//  KBEmotionController.swift
//  05-表情键盘
//
//  Created by kimbo on 15/12/28.
//  Copyright © 2015年 kimbo. All rights reserved.
//

import UIKit

class KBEmoticonsController: UIViewController {

    // MARK: - 属性
    /// 把表情插到的textView
    weak var textView: UITextView?
    
    /// cell的重用标识
    private var reuseIdentifier = "emoticonsCell"
    
    /// 所有表情包模型(只会从磁盘中加载一次)
    private let emoticonPackages = KBEmoticonPackage.packages
    
    /// toolBar按钮的起始tag
    var baseTag = 1000
    
    /// toolBar选中的按钮
    var selectedBtn: UIButton?
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init(textView: UITextView) {
        self.textView = textView
        
        super.init(nibName: nil, bundle: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI() //设置UI
    }

    //设置UI
    private func setupUI() {
        view.addSubview(collectionView)
        view.addSubview(toolBar)
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        //添加约束(VFL)
        //1 collectionView水平填充父控件
        // format: VFL语句 H: 表示水平 |父控件左边 | 父控件的右边 [] 有一个view [ view的左边 ]view的右边
        // 返回的是约束的数组
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv": collectionView]))
        
        //2 toolBar水平填充父控件
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb": toolBar]))
        
        // 垂直方向
        // 1.collectionView的顶部和父控件的顶部重合
        // 2.collectionView的底部和toolBar的顶部重合
        // 3.toolBar高44
        // 4.toolBar底部和父控件的底部重合
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv": collectionView, "tb": toolBar]))
        
        setupCollectionView()
        setupToolBar()
    }
    
    // 设置collectionView
    private func setupCollectionView() {
        collectionView.backgroundColor = UIColor(white: 0.8, alpha: 1)
        
        // 注册cell
        collectionView.registerClass(KBEmoticonsCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        // 设置数据源和代理
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    
    // 设置toolBar
    private func setupToolBar() {
        var items = [UIBarButtonItem]()
        var index = 0
        
        for emoticonPackage in emoticonPackages! {
            let name = emoticonPackage.group_name_cn
            // 设置toolBar每个按钮
            let btn = UIButton()
            btn.setTitle(name, forState: UIControlState.Normal)
            btn.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
            btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Highlighted)
            btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Selected)
            
            btn.sizeToFit()
            
            // 添加点击事件
            btn.tag = baseTag + index
            btn.addTarget(self, action: "toolBarButtonDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            // 默认选中最近表情包
            if index == 0 {
                switchSelectedButton(btn)
            }
            
            let item = UIBarButtonItem(customView: btn)
            
            items.append(item)
            
            // 添加弹簧
            let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            
            items.append(flexibleSpace)
            
            index++
        }
        
        //一次最后一根弹簧
        items.removeLast()
        
        toolBar.items = items
    }
    
    /// 点击toolBar按钮
    @objc private func toolBarButtonDidClick(btn: UIButton) {
        // 滚到对应的表情包
        collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: btn.tag - baseTag), atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
        
        // 选中点击的按钮
        switchSelectedButton(btn)
    }
    
    /// 选中点击的按钮
    private func switchSelectedButton(btn: UIButton) {
        selectedBtn?.selected = false
        
        btn.selected = true
        
        selectedBtn = btn
    }
    
    // MARK: - 懒加载
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: KBCollectionViewFlowLayout())
    
    /* toolBar */
    private lazy var toolBar: UIToolbar = UIToolbar()
}


// MARK: - 继承系统的流水布局，来覆盖prepareLayout来设置layout参数
class KBCollectionViewFlowLayout: UICollectionViewFlowLayout {
    // 覆盖父类prepareLayout
    override func prepareLayout() {
        super.prepareLayout()
        
        let itemWidth = collectionView!.frame.width / 7
        let itemHeight = collectionView!.frame.height / 3
        itemSize = CGSize(width: itemWidth, height: itemHeight)
        //取消间距
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        //水平滚动
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
    }
}


// MARK: - 扩展KBEmoticonsController 遵守UICollectionViewDataSource协议
extension KBEmoticonsController: UICollectionViewDataSource, UICollectionViewDelegate {
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        // 有多少个表情包就有多少组
        return emoticonPackages?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 表情包里有多少个表情就有多少个cell
        return emoticonPackages![section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! KBEmoticonsCell
        
        // 一个cell对应一个表情
        let emoticonPackage = emoticonPackages![indexPath.section]
        cell.emoticon = emoticonPackage.emoticons[indexPath.item]
        
        return cell
    }
    
    // 监听滚动来切换toolBar按钮的选中状态
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        // 获取正在显示的item的indexPath(取第十个，因为此表情键盘的item的frame是小数)
        let indexPath = collectionView.indexPathsForVisibleItems()[10]
        
        // 获取正在显示的section
        let section = indexPath.section
        
        //通过tag获取对应的button
        let btn = toolBar.viewWithTag(baseTag + section) as! UIButton
        
        switchSelectedButton(btn)
    }
    
    // 把点击选中的表情插到textView
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 取出对应表情包的对应表情
        let emoticonPackage = emoticonPackages![indexPath.section]
        
        let emoticon = emoticonPackage.emoticons[indexPath.item]
        
        // 把点击选中的表情插到textView
        textView?.insertEmoticon(emoticon)
        
        // 把点击的表情添加到最近包内(点击最近表情包里面的不参与排序)
        if indexPath.section != 0 {
            KBEmoticonPackage.addFavorateEmoticon(emoticon)
        }
    }
}

